package cn.e3mall.content.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.e3mall.common.jedis.JedisClient;
import cn.e3mall.common.pojo.EasyUIDataGridResult;
import cn.e3mall.common.util.E3Result;
import cn.e3mall.common.util.JsonUtils;
import cn.e3mall.content.service.ContentService;
import cn.e3mall.mapper.TbContentMapper;
import cn.e3mall.pojo.TbContent;
import cn.e3mall.pojo.TbContentExample;
import cn.e3mall.pojo.TbContentExample.Criteria;

@Service
public class ContentServiceImpl implements ContentService {

	@Autowired
	private TbContentMapper tbContentMapper;
	@Autowired
	private JedisClient jedisclient;
	@Value("${CONTENT_LIST}")
	private String CONTENT_LIST;
	
	
	
	//新增TbContent内容表
	@Override
	public E3Result addContent(TbContent content) {
		// 将内容数据插入到内容列表
		content.setCreated(new Date());
		content.setUpdated(new Date());
		//插入数据库
		tbContentMapper.insert(content);
		//redis缓存同步
		jedisclient.hdel(CONTENT_LIST, content.getCategoryId().toString());
		return E3Result.ok();
	}
	
	//分页根据categoryId查询TbContent内容表
	@Override
	public EasyUIDataGridResult getContentList(int page, int rows,Long categoryId) {
		PageHelper.startPage(page, rows);
		
		TbContentExample example = new TbContentExample();
		if (categoryId!=null&&categoryId!=0) {
			Criteria criteria = example.createCriteria();
			criteria.andCategoryIdEqualTo(categoryId);
		}
		
		List<TbContent> tbcontentList = tbContentMapper.selectByExample(example);
		
		PageInfo<TbContent> listInfo = new PageInfo<TbContent>(tbcontentList);
		EasyUIDataGridResult eGridResult = new EasyUIDataGridResult();
		eGridResult.setTotal(listInfo.getTotal());
		eGridResult.setRows(tbcontentList);
		
		return eGridResult;
	}

	//使用redis
	//根据内容分类id 查询分类列表
	@Override
	public List<TbContent> getContentListByCid(long cid) {
		try {
			String jsonstr = jedisclient.hget(CONTENT_LIST, cid+"");
			if(StringUtils.isNotBlank(jsonstr)){
				List<TbContent> list = JsonUtils.jsonToList(jsonstr, TbContent.class);
				return list; 
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		TbContentExample example = new TbContentExample();
		Criteria createria = example.createCriteria();
		createria.andCategoryIdEqualTo(cid);
		List<TbContent> list = tbContentMapper.selectByExampleWithBLOBs(example );
		try {
			jedisclient.hset(CONTENT_LIST,cid+"",JsonUtils.objectToJson(list));
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		return list;
	}
	
	


}
